package com.lanchewuyou.user.driver.lipeiui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lanchewuyou.user.driver.R;
import com.lanchewuyou.user.driver.ui.UploadPersonPhoActivity;
import com.lanchewuyou.user.driver.layouts.RadioBtnLayout;
import com.lanchewuyou.user.driver.modul.Config;
import com.lanchewuyou.user.driver.modul.OkHttpClientManager;
import com.squareup.okhttp.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 客户移交手续确认界面
 */

public class CustomDataActivity extends AppCompatActivity {
    private Toolbar mToolbar;
    private RadioBtnLayout baodanLayout, xingshizhengLayout, jiashizhengLayout, shenfenzhengLayout, yaoshiLayout, zhaopianLayout,
            beitaiLayout, huanbaobiaoLayout, sanjiaojiaLayout, miehuoqiLayout;
    private Button customDataBtn;
    public static CustomDataActivity instance;
    private Toast toast;
    private ProgressDialog progressDialog, progressUploadDialog;
    private static String DRIVERID;

    private void showTextToast(String msg) {
        if (toast == null) {
            toast = Toast.makeText(CustomDataActivity.this, msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_data);
        initViews();
        initLayouts();
        SharedPreferences sharedPreferences = getSharedPreferences(Config.PASSWORD_PATH, Activity.MODE_PRIVATE);
        DRIVERID = sharedPreferences.getString("driverid", "");
        instance = this;
        progressDialog.show();
        OkHttpClientManager.getAsyn(Config.DRIVERORDERDETAIL + "&driverid=" + DRIVERID + "&orderid=" + PickCarActivity.orderId, new OkHttpClientManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                showTextToast("没有获取到详情");
                progressDialog.dismiss();
            }

            @Override
            public void onResponse(String response) {
                Log.d("Pickcar", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString("status");
                    if (status.equals("1")) {
                        JSONObject info = jsonObject.getJSONObject("info");
                        String repair = info.getJSONObject("carinfo").getString("resinfo");
                        if (repair.equals("")) {
                            Log.d("repair", "kong");
                            progressDialog.dismiss();
                        } else {
                            progressDialog.dismiss();
                            new MaterialDialog.Builder(CustomDataActivity.this)
                                    .title("您已录入过客户移交信息")
                                    .content("确定将跳过此界面，取消将重新录入信息。")
                                    .positiveText("确定")
                                    .negativeText("取消")
                                    .callback(new MaterialDialog.ButtonCallback() {
                                        @Override
                                        public void onPositive(MaterialDialog dialog) {
                                            Intent intent = new Intent(CustomDataActivity.this, UploadPersonPhoActivity.class);
                                            intent.putExtra("from", "customdata");
                                            startActivity(intent);
                                            finish();
                                            CustomerInforActivity.instance.finish();
                                            CarfixInforActivity.instance.finish();
                                            CarInforActivity.instance.finish();
                                        }

                                        @Override
                                        public void onNegative(MaterialDialog dialog) {
                                            super.onNegative(dialog);
                                        }
                                    })
                                    .show();
                        }
                    } else {
                        progressDialog.dismiss();
                        showTextToast("没有获取到详情");
                    }
                } catch (JSONException e) {
                    progressDialog.dismiss();
                    e.printStackTrace();
                }
            }
        });
    }

    private void initViews() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle("客户移交手续（资料）情况");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("载入中");
        progressDialog.setMessage("请稍等");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(true);
        progressUploadDialog = new ProgressDialog(this);
        progressUploadDialog.setTitle("载入中");
        progressUploadDialog.setMessage("请稍等");
        progressUploadDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressUploadDialog.setCancelable(true);
        customDataBtn = (Button) findViewById(R.id.custom_data_next_btn);
        customDataBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressUploadDialog.show();
                Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
                Map<String, String> map = getRadioMap();
                String s = gson.toJson(map);
                Log.d("TAG", s);
                RequestQueue mQueue = Volley.newRequestQueue(CustomDataActivity.this);
                String url = Config.CUSTOMDATA + PickCarActivity.orderId + "&driverid=" + DRIVERID + "&resinfo=" + s;
                StringRequest stringRequest = new StringRequest(url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d("TAG", response);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String status = jsonObject.getString("status");
                                    Log.d("carfix", status);
                                    if (status.equals("1")) {
                                        Log.d("carfix", "信息上传成功");
                                        Intent intent = new Intent(CustomDataActivity.this, UploadPersonPhoActivity.class);
                                        intent.putExtra("from", "customdata");
                                        startActivity(intent);
                                        finish();
                                        CustomerInforActivity.instance.finish();
                                        CarfixInforActivity.instance.finish();
                                        CarInforActivity.instance.finish();
                                        progressUploadDialog.dismiss();
                                    } else {
                                        showTextToast("信息上传失败");
                                        progressUploadDialog.dismiss();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    progressUploadDialog.dismiss();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("TAG", error.getMessage(), error);
                        progressUploadDialog.dismiss();
                    }
                });
                mQueue.add(stringRequest);
            }
        });
    }

    private void initLayouts() {
        baodanLayout = (RadioBtnLayout) findViewById(R.id.baodan_check);
        baodanLayout.setTitleText("保单原件");
        xingshizhengLayout = (RadioBtnLayout) findViewById(R.id.xingshizheng_check);
        xingshizhengLayout.setTitleText("行驶证原件");
        jiashizhengLayout = (RadioBtnLayout) findViewById(R.id.jiashizheng_check);
        jiashizhengLayout.setTitleText("驾驶证原件");
        shenfenzhengLayout = (RadioBtnLayout) findViewById(R.id.shenfenzheng_check);
        shenfenzhengLayout.setTitleText("身份证原件");
        yaoshiLayout = (RadioBtnLayout) findViewById(R.id.yaoshi_check);
        yaoshiLayout.setTitleText("车钥匙");
        yaoshiLayout.setRadioText();
        zhaopianLayout = (RadioBtnLayout) findViewById(R.id.zhaopian_check);
        zhaopianLayout.setTitleText("现场照片");
        beitaiLayout = (RadioBtnLayout) findViewById(R.id.beitai_check);
        beitaiLayout.setTitleText("备胎");
        huanbaobiaoLayout = (RadioBtnLayout) findViewById(R.id.huanbaobiao_check);
        huanbaobiaoLayout.setTitleText("环保标");
        sanjiaojiaLayout = (RadioBtnLayout) findViewById(R.id.sanjiaojia_check);
        sanjiaojiaLayout.setTitleText("三脚架");
        miehuoqiLayout = (RadioBtnLayout) findViewById(R.id.miehuoqi_check);
        miehuoqiLayout.setTitleText("灭火器");
    }

    private Map<String, String> getRadioMap() {
        RadioBtnLayout[] btnLayouts = new RadioBtnLayout[]{baodanLayout, xingshizhengLayout, jiashizhengLayout, shenfenzhengLayout, yaoshiLayout, zhaopianLayout,
                beitaiLayout, huanbaobiaoLayout, sanjiaojiaLayout, miehuoqiLayout};
        Map<String, String> map = new LinkedHashMap<>();
        for (int i = 0; i < 10; i++) {
            map.put(Integer.valueOf(i + 1).toString(), btnLayouts[i].getCheckId());
        }
        return map;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_custom_data, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}
